﻿using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using NLog;
using NLog.Extensions.Logging;

namespace NLogDemo
{
    internal class Program
    {
        private static void Main(string[] args)
        {
            //1.拿到logger对象实例
            var logger = LogManager.GetCurrentClassLogger();

            //2.配置logger  先创建一个json文件  appsettings.json
            var config = new ConfigurationBuilder()
                .SetBasePath(Environment.CurrentDirectory)
                .AddJsonFile("appsettings.json")
                .Build();

            //3.读取配置
            var nlogConifg = config.GetSection("NLog");

            //4.关联配置
            LogManager.Configuration = new NLogLoggingConfiguration(nlogConifg);

            //5.创建一个服务集合
            var services = new ServiceCollection()
                .AddLogging(loggerBuilder => {
                    loggerBuilder.ClearProviders();//清楚其他日志的提供者
                    loggerBuilder.SetMinimumLevel(Microsoft.Extensions.Logging.LogLevel.Trace);//设置等级
                    loggerBuilder.AddNLog();
                });

            //6.添加对象到服务里  这里需要添加我们要用日志的对象
            services.AddScoped<Person>();

            //7.创建一个服务定位器
            using var serviceProvider = services.BuildServiceProvider();

            //8.取出对象
           var person= serviceProvider.GetRequiredService<Person>();

            //9.使用
            person.DoSomethings();

            person.Warningthings();


        }



    }

    public class Person
    {
        private readonly ILogger<Person> _logger;
        public Person(ILogger<Person> _logger)
        {
            this._logger = _logger; 
        }

        public void DoSomethings()
        {
            _logger.LogInformation("某人在吃饭");
        }

        public void Warningthings()
        {
            _logger.LogWarning("某人吃饭噎住了");
        }
    }

    public class Person1
    {
        private readonly ILogger<Person1> _logger;
        public Person1(ILogger<Person1> _logger)
        {
            this._logger = _logger;
        }

        public void DoSomethings()
        {
            _logger.LogInformation("某人在吃饭");
        }

        public void Warningthings()
        {
            _logger.LogWarning("某人吃饭噎住了");
        }
    }
}